import os
import subprocess
import time
import json
from datetime import datetime

def pull_logs():
    # 格式化日期时间字符串
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    log_filename = f"{timestamp}_SYSLOG"
    
    # 执行 adb pull 命令
    # 创建目录
    os.makedirs(log_filename, exist_ok=True)
    print(f"{datetime.now()} - Directory {log_filename} created")

    push_result = run_command(f"adb pull /media/sdcard/log/SYSLOG/kernel.log ./{log_filename}/")
    print(f"{datetime.now()} - {push_result}")
    push_result = run_command(f"adb pull /media/sdcard/log/SYSLOG/kernel.log.0 ./{log_filename}/")
    print(f"{datetime.now()} - {push_result}")
    push_result = run_command(f"adb pull /media/sdcard/log/SYSLOG ./{log_filename}")
    print(f"{datetime.now()} - {push_result}")

def run_command(command):
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True)
        return result.stdout
    except KeyboardInterrupt:
        print(f"{datetime.now()} - \nOperation interrupted by user. Exiting...")
        exit(0)

def load_config(config_file):
    with open(config_file, 'r') as file:
        config = json.load(file)
    return config

def main():
    config = load_config('config.json')
    update_package_paths = config['update_package_paths']
    operation_count = 0
    max_timeout = 600  # 10 minutes in seconds

    try:
        while True:
            for update_package_path in update_package_paths:
                while True:
                    start_time = time.time()
                    if time.time() - start_time > max_timeout:
                        print(f"{datetime.now()} - Timeout reached. Exiting...")
                        pull_logs()
                        return

                    operation_count += 1
                    print(f"{datetime.now()} - Operation attempt: {operation_count}")

                    # Step 1: Push the update package to the device
                    print(f"{datetime.now()} - Pushing update package to device from {update_package_path}...")
                    push_result = run_command(f"adb push {update_package_path} /media/sdcard/UpdatePackage/updatepackage.tgz")
                    if "1 file pushed" not in push_result:
                        print(f"{datetime.now()} - Failed to push update package.")
                        time.sleep(5)
                        continue
                    print(f"{datetime.now()} - {push_result}")

                    # Step 2: Create a flag file on the device
                    print(f"{datetime.now()} - Creating flag file on device...")
                    touch_result = run_command("adb shell touch /media/sdcard/UpdatePackage/flagfile.txt")
                    if touch_result:
                        print(f"{datetime.now()} - Failed to create flag file.")
                        time.sleep(5)
                        continue

                    # Step 3: Wait for device to reboot
                    print(f"{datetime.now()} - Waiting for device to reboot...")
                    # Wait for device to disconnect
                    while True:
                        devices = run_command("adb devices")
                        if "List of devices attached" in devices and len(devices.splitlines()) <= 2:
                            print(f"{datetime.now()} - Device disconnected.")
                            break
                        if time.time() - start_time > max_timeout:
                            print(f"{datetime.now()} - Timeout waiting for device to disconnect.")
                            pull_logs()
                            return
                        print(f"{datetime.now()} - 1 : {devices}, {len(devices.splitlines())}")
                        time.sleep(5)

                    # Wait for device to reconnect
                    while True:
                        devices = run_command("adb devices")
                        if "List of devices attached" in devices and len(devices.splitlines()) > 2:
                            print(f"{datetime.now()} - Device reconnected.")
                            print(f"{datetime.now()} - {devices}")
                            break
                        if time.time() - start_time > max_timeout:
                            print(f"{datetime.now()} - Timeout waiting for device to reconnect.")
                            pull_logs()
                            return
                        print(f"{datetime.now()} - 2 : {devices}, {len(devices.splitlines())}")
                        time.sleep(5)

                    # Step 4: Get FOTA info and check if FOTA update succeeded
                    print(f"{datetime.now()} - Waiting for FOTA update to succeed...")
                    while True:
                        fota_info = run_command("adb shell fotainfo --get-all")
                        print(f"{datetime.now()} - {fota_info}")

                        if "Erase Count:" in fota_info and "FOTA STAT:SUCCEED (0)" in fota_info:
                            print(f"{datetime.now()} - FOTA update succeeded.")
                            break
                        else:
                            print(f"{datetime.now()} - FOTA update not yet succeeded, checking again in 10 seconds...")
                            time.sleep(10)

                        if time.time() - start_time > max_timeout:
                            print(f"{datetime.now()} - Timeout waiting for FOTA update to succeed.")
                            pull_logs()
                            return

                    # Step 5: Wait for /media/sdcard/UpdatePackage/ to be empty
                    print(f"{datetime.now()} - Waiting for /media/sdcard/UpdatePackage/ to be empty...")
                    while True:
                        files = run_command("adb shell ls /media/sdcard/UpdatePackage/")
                        if not files.strip():
                            print(f"{datetime.now()} - /media/sdcard/UpdatePackage/ is empty. Upgrade succeeded.")
                            break
                        if time.time() - start_time > max_timeout:
                            print(f"{datetime.now()} - Timeout waiting for /media/sdcard/UpdatePackage/ to be empty.")
                            pull_logs()
                            return
                        print(f"{datetime.now()} - Files in /media/sdcard/UpdatePackage/: {files.strip()}")
                        time.sleep(10)

                    time.sleep(10)
                    break

        pull_logs()

    except KeyboardInterrupt:
        print(f"{datetime.now()} - \nOperation interrupted by user. Exiting...")

if __name__ == "__main__":
    main()
